package com.si.control.action;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Random;

public class PreservedCollageAction extends CollageAction {

	private final Random random;

	public PreservedCollageAction() {
		this.random = new Random();
	}

	@Override
	protected BufferedImage doCollage(final List<BufferedImage> argument) throws Exception {
		final int length = argument.size();
		final BufferedImage result = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
		// Randomly select one to preserve.
		final int rootIndex = (length-1) & this.random.nextInt();
		final BufferedImage root = argument.get(rootIndex);
		final int xlimit = Math.min(root.getWidth(), this.width);
		final int ylimit = Math.min(root.getHeight(), this.height);
		for(int x = 0; x < xlimit; x++) {
			for(int y = 0; y < ylimit; y++) {
				final int rgb = root.getRGB(x, y);
				result.setRGB(x, y, rgb);
			}
		}
		// Take one byte from each image, loop if not enough.
		int index = 0;
		for(int x = 0; x < this.width; x++) {
			for(int y = 0; y < this.width; y++) {
				// Randomly decide if replace with 50% chance.
				if(!this.replace()) continue;
				final BufferedImage image = argument.get(index);
				final int w = image.getWidth();
				final int h = image.getHeight();
				final int xi = (w-1) & this.random.nextInt();
				final int yi = (h-1) & this.random.nextInt();
				final int rgb = image.getRGB(xi, yi);
				result.setRGB(x, y, rgb);
				index++;
				if(index == length) index = 0;
			}
		}
		return result;
	}
	
	private boolean replace() {
		final double d = this.random.nextDouble();
		if(d < 0.5) return true;
		return false;
	}
}
